<?php

$dbuser = "";
$dbpwd = "";
$dbname = "";

////////////////////////////////////////////////////////////////////////

$corpname = get_string('corp', $_REQUEST, 100); // corp name
$type = get_unsigned_number('type', $_REQUEST); // 0:kills - 1:losses
$init = (array_key_exists('init', $_REQUEST) ? 1 : 0); // pull 6 months of kills

////////////////////////////////////////////////////////////////////////

function get_unsigned_number($name, $from){
	if(array_key_exists($name, $from)){
		$n = $from[$name];
		if(is_numeric($n) && $n > 0) return $n;
	}
	return 0;
}
function get_string($name, $from, $maxlen){
	if(array_key_exists($name, $from)){
		$s = $from[$name];
		if(is_string($s) && strlen($s) <= $maxlen) return stripslashes($s);
	}
	return "";
}
function db_query($q){
	//     on -->   failure     no-match    match
	// return -->   FALSE       TRUE        array

	$ra = array();
	if($ro = mysql_query($q)){
		if(!is_resource($ro)) return 1;
		while($row = mysql_fetch_row($ro)) $ra[] = $row;
		mysql_free_result($ro);
	} else {
		printf("database query failed: %s<br>", mysql_error());
	}
	if(count($ra) == 0) return 0; else return $ra;
}
function db_query_value($q){
	$x = db_query($q);
	if(is_array($x) && count($x) == 1){
		if(count($x[0]) == 1) return $x[0][0];
		return $x[0];
	}
	return 0;
}

////////////////////////////////////////////////////////////////////////

mysql_connect("", $dbuser, $dbpwd)
	or die("could not connect to database: ". mysql_error());
mysql_select_db($dbname);

if(!empty($corpname))
	$corp = db_query_value("SELECT crp_id FROM kb3_corps WHERE crp_name = '".mysql_escape_string($corpname)."';"); // hirr = 500
if($corp == 0) die("invalid corp name '$corpname'");

$t = time();
$parts = getdate($t);
$today = $t - ($parts['seconds'] + $parts['minutes']*60 + $parts['hours']*3600);
if($init) $yesterday = $today - 16070400; // six months ago
else $yesterday = $today - 604800; // one week ago

if($type == 0){ // kills

	$kills = db_query("SELECT kll_id, plt_externalid, UNIX_TIMESTAMP(kll_timestamp), sys_id FROM kb3_kills, kb3_inv_detail, kb3_systems, kb3_pilots"
	." WHERE ind_kll_id = kll_id AND sys_id = kll_system_id AND plt_id = ind_plt_id AND plt_externalid != 0 AND ind_crp_id = $corp"
	." AND UNIX_TIMESTAMP(kll_timestamp) >= $yesterday AND UNIX_TIMESTAMP(kll_timestamp) < $today;");
	if(is_array($kills))
		foreach($kills as $kill)
			echo "$kill[0] $kill[1] $kill[2] $kill[3]\n";

//	echo "<br><br>".count($kills); // 14471 (14344)

} else if($type == 1){ // losses

	$losses = db_query("SELECT kll_id, kll_victim_id, UNIX_TIMESTAMP(kll_timestamp), sys_id FROM kb3_kills, kb3_systems"
	." WHERE sys_id = kll_system_id AND kll_crp_id = $corp"
	." AND UNIX_TIMESTAMP(kll_timestamp) >= $yesterday AND UNIX_TIMESTAMP(kll_timestamp) < $today;");
	if(is_array($losses))
		foreach($losses as $loss)
			echo "$loss[0] $loss[1] $loss[2] $loss[3]\n";

}

//echo "<br><br>".(time()-$t)." seconds";

mysql_close();
?>
